package com.totoro.tyrank.executor.action.impl;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.ActionConst;
import com.totoro.tyrank.constants.CommandActionTypeConst;
import com.totoro.tyrank.executor.action.ActionExecutor;
import com.totoro.tyrank.utils.PapiUtil;
import com.totoro.tyrank.utils.StrUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

public class CommandActionExecutor implements ActionExecutor {
    @Override
    public void execute(String actionText, Player player) {
        String command = StrUtil.getContentAfter(actionText, ActionConst.COMMAND);
        // 先解析PAPI变量
        command = PapiUtil.parseStrPapiVariable(player, command);
        // 如果是以OP权限
        if(command.startsWith(CommandActionTypeConst.OP)) {
            command = StrUtil.getContentAfter(command, CommandActionTypeConst.OP).trim();
            // 获取玩家原OP
            boolean isOp = player.isOp();
            try {
                player.setOp(true);
                Bukkit.dispatchCommand(player, command);
                player.setOp(isOp);
            } catch (Exception e) {
                player.setOp(isOp);
            }
        }
        // 如果是以console
        else if (command.startsWith(CommandActionTypeConst.CONSOLE)) {
            command = StrUtil.getContentAfter(command, CommandActionTypeConst.CONSOLE).trim();
            Bukkit.dispatchCommand(TyRank.getInstance().getServer().getConsoleSender(), command);
        }
        // 默认执行
        else {
            Bukkit.dispatchCommand(player, command);
        }
    }
}
